//
//  RegistViewController.m
//  EnglishTalk
//
//  Created by DING FENG on 6/27/14.
//  Copyright (c) 2014 ishowtalk. All rights reserved.
//

#import "SRCellPhoneViewController.h"
#include "SRCountdownButton.h"
#import <UMMobClick/MobClick.h>
#import "SRCommonConstants.h"
#import "SRLoginManager.h"
#import "FCUtil.h"
#import "FZSpeechVerificationView.h"
#import "FZStyleSheet.h"
#import "RIButtonItem.h"

@interface SRCellPhoneViewController ()<UITextFieldDelegate, UIAlertViewDelegate,FZSpeechVerificationViewDelegate,SRCountdoenButtonDelegate>

@property (strong, nonatomic) UITextField  *phoneTextField;
@property (strong, nonatomic) UITextField  *passwordTextField;
@property (strong, nonatomic) UITextField  *checkNum;

@property (strong, nonatomic) SRCountdownButton *checkingButton;

/**
 *  语音验证视图
 */
@property (strong, nonatomic) FZSpeechVerificationView *sVerView;
@property (strong, nonatomic) FZStyleSheet * css ;
@end

@implementation SRCellPhoneViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.css = [FZStyleSheet currentStyleSheet];
    self.title = @"绑定手机号";
    
    self.view.backgroundColor = [UIColor colorWithRed:248./255 green:248./255 blue:248./255 alpha:1];
    
    CGFloat backViewY = 20;
    if (!self.hideCustomNavigationView) {
        UIView  *navBackView = [[UIView  alloc]  initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 44)];
        navBackView.backgroundColor = [UIColor colorWithRed:248./255 green:247./255 blue:247./255 alpha:1];
        
        UILabel  *l = [[UILabel  alloc]  initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        l.text = @"注册";
        l.backgroundColor = [UIColor  clearColor];
        l.textAlignment = NSTextAlignmentCenter;
        [navBackView  addSubview:l];
        
        UIButton  *backButton = [[UIButton   alloc]   initWithFrame:CGRectMake(0, 0, 100/2.1, 90/2.1)];
        [backButton  setImage:[UIImage  imageNamed:@"返回.png"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backButton) forControlEvents:UIControlEventTouchUpInside];
        [navBackView addSubview:backButton];
        backViewY = 84;
    }
    
    //back view
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, backViewY, SCREEN_WIDTH, 200)];
    backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backView];
    
    //phone TF
    self.phoneTextField = [[UITextField  alloc]  initWithFrame:CGRectMake(15, 0, 300, 44)];
    self.phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneTextField.backgroundColor = [UIColor   whiteColor];
    [self.phoneTextField  setFont:[UIFont   boldSystemFontOfSize:13]];
    self.phoneTextField.delegate = self;
    [self.phoneTextField setTextColor:[UIColor  grayColor]];

    //password TF
    self.passwordTextField = [[UITextField  alloc]  initWithFrame:CGRectMake(15, 55-10-3, 300, 44)];
    self.passwordTextField.backgroundColor = [UIColor   whiteColor];
    [self.passwordTextField  setFont:[UIFont   boldSystemFontOfSize:13]];
    [self.passwordTextField setReturnKeyType:UIReturnKeyDone];
    self.phoneTextField.placeholder = @"手机号码";
    self.passwordTextField.placeholder = @"6-18位字母数字组合密码";
    self.passwordTextField.secureTextEntry = YES;
    self.passwordTextField.delegate = self;
    [self.passwordTextField setTextColor:[UIColor  grayColor]];
    
    //check num TF
    self.checkNum = [[UITextField alloc] initWithFrame:CGRectMake(15, 100-5-15, 300, 44)];
    //    [self.checkNum setBackground:[UIImage imageNamed:@"input_box"]];
    [self.checkNum setFont: [UIFont systemFontOfSize:13]];
    self.checkNum.placeholder = @"输入验证码";
    self.checkNum.textAlignment = NSTextAlignmentLeft;
    [self.checkNum setReturnKeyType:UIReturnKeyDone];
    self.checkNum.keyboardType = UIKeyboardTypeNumberPad;
    self.checkNum.delegate = self;
    
    [backView addSubview:_phoneTextField];
    [backView addSubview:_passwordTextField];
    [backView addSubview:_checkNum];
    
    //    btn-.png
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UIButton  *registButton = [[UIButton  alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(self.checkNum.frame) + 55, SCREEN_WIDTH-20, 40)];
    [registButton  setBackgroundImage:[UIImage imageWithColor:css.colorOfMainTint]  forState:UIControlStateNormal];
    [registButton  setTitle:@"提交绑定" forState:UIControlStateNormal];
    
    [registButton  addTarget:self action:@selector(registButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [backView  addSubview:registButton];
    registButton.layer.cornerRadius = css.buttonCornerRadius;
    registButton.layer.masksToBounds = YES;
    
    // 验证码按钮 - Kim
    
    self.checkingButton = [[SRCountdownButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 110 - 15, CGRectGetMinY(self.checkNum.frame) + 2, 110, 42)];
//    [self.getCheckNumberButton setEnabled:YES];
//    self.getCheckNumberLabel.textColor = [FZStyleSheet currentStyleSheet].colorOfGreenButtonNormal;
    self.checkingButton.delegate = self;
//    [self.checkingButton setBackgroundImage:[UIImage imageWithColor:css.colorOfMainTint]  forState:UIControlStateNormal];
//    [self.checkingButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.checkingButton setEnabled:NO];
    [self.checkingButton addTarget:self action:@selector(checkingButton:)   forControlEvents:UIControlEventTouchUpInside]; // checkingButton
    [backView addSubview:self.checkingButton];
    // 验证码输入框 - Kim
    self.checkingButton.layer.cornerRadius = css.buttonCornerRadius;
    self.checkingButton.layer.masksToBounds = YES;
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(10, 40+2, SCREEN_WIDTH - 10, 1)];
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(10, 80+6-5, SCREEN_WIDTH - 10, 1)];
    line1.backgroundColor = [UIColor colorWithRed:248./255 green:248./255 blue:248./255 alpha:1];
    line2.backgroundColor = [UIColor colorWithRed:248./255 green:248./255 blue:248./255 alpha:1];
    [backView addSubview:line1];
    [backView addSubview:line2];
    
    self.sVerView = [[FZSpeechVerificationView alloc] init];
    self.sVerView.delegate = self;
    [self.view addSubview:self.sVerView];
    WEAKSELF
    [self.sVerView mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.equalTo(weakSelf.checkNum.mas_bottom).offset(10);
        make.trailing.equalTo(weakSelf.view).offset(-15);
        make.width.mas_equalTo(220);
        make.height.mas_equalTo(35);
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChangeNotification) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)dealloc{
    [self.sVerView clear];
}

-(void)backButton
{
    [self.navigationController   popViewControllerAnimated:YES];
}
-(void)gotologin
{
}

#pragma mark TextFiledDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    if(textField == self.phoneTextField)
//    {
//        NSString *phoneText = textField.text;
//        if(phoneText.length > 0){
//            //语音和短信都可点击
//            [self.checkingButton setEnabled:YES];
//            self.checkingButton.timelabel.textColor = self.css.colorOfGreenButtonNormal;
//            [self.sVerView setAvailable:YES];
//            return YES;
//        }
//        else
//        {
//            [self.checkingButton setEnabled:NO];
//            self.checkingButton.timelabel.textColor = self.css.colorOfGreenButtonDisabled;
//            [self.sVerView setAvailable:NO];
//            return YES;
//        }
//    }
    if(textField == self.passwordTextField){
        NSString *passwordText = textField.text;
        if(passwordText.length >= 18){
            return NO;
        }
    }

    return YES;
}
-(void)textFieldTextDidChangeNotification
{
    NSString *phoneText = self.phoneTextField.text;
    if(phoneText.length > 0){
        //语音和短信都可点击
        [self.checkingButton setEnabled:YES];
        self.checkingButton.timelabel.textColor = self.css.colorOfGreenButtonNormal;
        [self.sVerView setAvailable:YES];
    }
    else
    {
        [self.checkingButton setEnabled:NO];
        self.checkingButton.timelabel.textColor = self.css.colorOfGreenButtonDisabled;
        [self.sVerView setAvailable:NO];
    }

}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

// 获取验证码按钮功能 - Kim
- (void)checkingButton:(UIButton *)sender
{
    
    [self.phoneTextField  resignFirstResponder];
    [self.passwordTextField  resignFirstResponder];
    [self.checkNum  resignFirstResponder];
    
    NSString  *mobile = self.phoneTextField.text;
    if (!mobile || [mobile length] < 11) {
        [self showHUDHintWithText:@"手机号错误！"];
        [self.checkingButton resetTheState];
        return;
    }
    
    if (![FCUtil isValidateMobilePhoneNumber:mobile]) {
        [self showHUDHintWithText:@"请填写正确的手机号码"];
        [self.checkingButton resetTheState];
        return;
    }
    [self startProgressHUD];
   
    NSString *urlString = [[SRAPICreater sharedInstance] APIWithName:@"user_mobile_code"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:mobile forKey:@"mobile"];
    [parameters setValue:@(1) forKey:@"isreset"];
    [parameters setValue:@(2) forKey:@"type"];
    WEAKSELF
    
    [[SRNetWorkManager sharedInstance] GET:urlString needCache:NO parameters:parameters responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject) {
        if (statusCode != kFZRequestStatusCodeSuccess){
            [weakSelf showHUDHintWithText:message];
            
                //start-- add by zhouyongyang 验证出现问题则重置验证按钮
            [weakSelf.checkingButton resetTheState];
                //end--
        }else{
            [weakSelf showHUDHintWithText:@"HUDMessageSend"];
            [weakSelf.sVerView setAvailable:NO];
            [weakSelf.checkingButton touchesBegan];
        }

    } failure:^(id responseObject, NSError *error) {
        [weakSelf showHUDError];
        [weakSelf.checkingButton resetTheState];
    }];
}

    

// 注册按钮修改 - Kim
-(void)registButtonAction
{
    [self.phoneTextField  resignFirstResponder];
    [self.passwordTextField  resignFirstResponder];
    [self.checkNum  resignFirstResponder];
    
    if (self.phoneTextField.text.length < 1)
    {
        [self showHUDHintWithText:@"请填写你的手机号码"];
        return;
    }
    
    if (self.passwordTextField.text.length < 1)
    {
        [self showHUDHintWithText:@"请设置密码"];
        return;
    }
    
    if (![FCUtil isValidatePassword:self.passwordTextField.text]) {
        [self showHUDErrorMessage:@"changePSW_tooSimple"];
        return;
    }
    if (self.checkNum.text.length < 1)
    {
        [self showHUDHintWithText:@"请填写正确的验证码"];

        return;
    }
    
    NSString *mobile = self.phoneTextField.text;
    NSString *password= self.passwordTextField.text;
    NSString *checkNumStr = self.checkNum.text;

    NSString *urlString = [[SRAPICreater sharedInstance] APIWithName:@"user_checkTieupMobile"];
    NSDictionary *parameters = [@{} mutableCopy];
    [parameters setValue:mobile forKey:@"mobile"];
//    [parameters setValue:[FCUtil md5HexString:password] forKey:@"password"];
    [parameters setValue:password forKey:@"password"];

    [parameters setValue:checkNumStr forKey:@"code"];

    ESWeakSelf
    [[SRNetWorkManager sharedInstance] POST:urlString needCache:NO parameters:parameters responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject) {
        ESStrongSelf
        if (statusCode == 1) {
            [_self.phoneTextField resignFirstResponder];
            [_self.passwordTextField resignFirstResponder];
            [_self.checkNum resignFirstResponder];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"注意" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        } else {
            [_self showHUDHintWithText:message];
        }
    } failure:^(id responseObject, NSError *error) {
        ESStrongSelf
        [_self showHUDError];
    }];
}

-(BOOL) NSStringIsValidPhone:(NSString *)checkString
{
    NSString *phoneRegex = self.phoneTextField.text;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [emailTest evaluateWithObject:checkString];
}

#pragma mark - AppDelegate methods

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

}
-(void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter]postNotificationName: @"Refresh" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}
- (void)showSuccessAlertView:(id)responseObject {
    [self.checkNum resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    [self.phoneTextField resignFirstResponder];
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号绑定成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alertView show];

}

- (void)GetLoginAndRefreshUserInfo:(id)responseObject
{
    [[SRLoginManager sharedManager] updateUserInfo:responseObject[@"data"]];
//    NSString *hadLogin= [[User sharedInstance].userinfoDict objectForKey:@"hadLogin"];
//    [[User sharedInstance] reloadUserInfo:responseObject hadLogin:hadLogin isGuest:@"NO"];
    
    //发送绑定成功通知
//    [[NSNotificationCenter defaultCenter] postNotificationName:FZBindCellPhoneSucessNotification object:nil];
    
    [self.navigationController popViewControllerAnimated:YES];
    
    if(self.successBlock){
        self.successBlock();
    }
}

-(void)viewDidAppear:(BOOL)animated{
    
}

#pragma mark - uialertview delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSString  *mobile = self.phoneTextField.text;
        NSString  *password= self.passwordTextField.text;
        
        [SRLoginUser setuserLoginAcount:mobile];
        [SRLoginUser setuserLoginPassword:password];
        
        NSString  *checkNumStr = self.checkNum.text;
        NSString *url = [[SRAPICreater sharedInstance] APIWithName:@"user_tieup_mobile"];
        NSString* encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:
                                NSUTF8StringEncoding];
        
        NSDictionary *parameters = [@{} mutableCopy];
        [parameters setValue:mobile forKey:@"mobile"];
//        [parameters setValue:[FCUtil md5HexString:password] forKey:@"password"];
        [parameters setValue:password forKey:@"password"];

        [parameters setValue:checkNumStr forKey:@"code"];
        [parameters setValue:[SRLoginUser userID] forKey:@"uid"];
        [parameters setValue:[SRLoginUser authToken] forKey:@"auth_token"];
        
        [self.phoneTextField resignFirstResponder];
        [self.passwordTextField resignFirstResponder];
        [self.checkNum resignFirstResponder];
        
        WEAKSELF
        [[SRNetWorkManager sharedInstance] POST:encodedUrl needCache:NO parameters:parameters responseClass:nil success:^(NSInteger statusCode, NSString *message, id dataObject) {
            [weakSelf showHUDHintWithText:message];
        } failure:^(id responseObject, NSError *error) {
            [weakSelf showHUDError];
        }];
        
    }
}


#pragma mark FZSpeechVerificationViewDelegate
/**
 *  剩余超时的时间
 *
 *  @param time 
 */
- (void)sVerRemainTime:(NSInteger)time{
    if(time <= 0){
        //超时
        [self.checkingButton resetTheState];
    }
}

/**
 *  请求进度显示
 */
-(void)sVerStartProgress{
    [self startProgressHUD];
}

/**
 *  请求进度消失
 *
 *
 */
-(void)sVerStopProgress:(NSString*)msg{
    [self stopProgressHUD];
    if(msg){
        [self showHUDErrorMessage:msg];
    }else{
        [self.checkingButton setEnabled:NO];
        self.checkingButton.timelabel.textColor = self.css.colorOfGreenButtonDisabled;
    }
}

/**
 *  获取验证需要的参数
 *
 *
 */
-(NSMutableDictionary*)sVerParamas{
    NSString  *mobile = self.phoneTextField.text;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:mobile forKey:@"mobile"];
    [parameters setValue:@(1) forKey:@"isreset"];
    [parameters setValue:@(2) forKey:@"type"];
    return parameters;
}

#pragma mark SRCountdoenButtonDelegate
- (void)updateDone{
    
}

- (void)cdBtnUpdateTime:(NSInteger)time{
    if(time <= 0){
        [self.sVerView setAvailable:YES];
    }
    else
    {
        [self.sVerView setAvailable:NO];
    }
}

@end
